import React, { useEffect, useMemo, useRef, useState } from "react";
import { Empty, Spin, Typography } from "antd";
import { useDebounceFn, useRequest, useTitle } from "ahooks";

import styles from "./common.module.scss";
import QuestionCard from "../components/QuestionCard";
import { QuestionType } from "../../types";
import ListSearch from "../components/ListSearch";
import { useSearchParams } from "react-router-dom";
import { getQuestionListService } from "../../services/question";
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from "../../constants";

const { Title } = Typography;

const List: React.FC = () => {
  useTitle("新问卷 - 我的问卷");
  const [searchParams] = useSearchParams();
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || "";
  useEffect(() => {
    setStarted(false);
    setPage(1);
    setList([]);
    setTotal(0);
  }, [keyword]);
  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: LIST_PAGE_SIZE,
        keyword,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result = {}) {
        const { list: l = [], total = 0 } = result;
        setPage(page + 1);
        setList(list.concat(l));
        setTotal(total);
      },
    }
  );
  const [started, setStarted] = useState(false);
  const [page, setPage] = useState(1);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const haveMoreData = total > list.length;
  const mainRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      if (loading) return;
      const elem = containerRef.current;
      if (elem === null) return;
      const domReact = elem.getBoundingClientRect();
      if (domReact === null) return;
      const { bottom } = domReact;
      if (bottom <= document.body.clientHeight) {
        load();
        setStarted(true);
      }
    },
    { wait: 500 }
  );

  useEffect(() => {
    tryLoadMore();
  }, [searchParams]);

  useEffect(() => {
    const mainDom = mainRef.current;

    if (haveMoreData && mainDom) {
      mainDom.addEventListener("scroll", tryLoadMore);
    }

    return () => {
      if (mainDom) mainDom.removeEventListener("scroll", tryLoadMore);
    };
  }, [searchParams, haveMoreData]);

  const LoadMoreContentElem = useMemo(() => {
    if (!started || loading) return <Spin />;
    if (total === 0) return <Empty description="暂无数据" />;
    if (!haveMoreData) return <span>没有更多了</span>;
    return <span>加载更多</span>;
  }, [started, loading, total, haveMoreData]);

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.main} ref={mainRef}>
        <div>
          {list.length > 0 &&
            list.map((i: QuestionType) => <QuestionCard key={i.id} {...i} />)}
        </div>
        <div className={styles.footer} ref={containerRef}>
          {LoadMoreContentElem}
        </div>
      </div>
    </>
  );
};

export default List;
